<template>
	<xn-form-container title="数据库字段" :width="700" :open="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="数据源：" name="dbsId">
						<a-select
							:disabled="true"
							v-model:value="formData.dbsId"
							:options="dbsList"
							style="width: 100%"
							placeholder="请选择数据源"
							@select="getDbTables(formData.dbsId)"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="表名称：" name="tableName">
						<a-select
							:disabled="true"
							v-model:value="formData.tableName"
							:options="tableList"
							style="width: 100%"
							placeholder="请选择表"
							@select="getDbColumns(formData.dbsId, formData.tableName)"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12" v-if="!isEdit">
					<a-form-item label="字段名称：" name="columnName">
						<a-input v-model:value="formData.columnName" placeholder="请输入字段名称" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12" v-if="!!isEdit">
					<a-form-item label="字段名称：" name="newColumnName">
						<a-input v-model:value="formData.newColumnName" placeholder="请输入字段名称" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="字段类型：" name="columnType">
						<a-select
							v-model:value="formData.columnType"
							placeholder="请选择字段类型"
							:options="columnTypeOptions"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="字段长度：" name="columnLength">
						<a-input-number
							:min="0"
							style="width: 100%"
							v-model:value="formData.columnLength"
							placeholder="请输入字段长度"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="字段注释：" name="columnRemark">
						<a-input v-model:value="formData.columnRemark" placeholder="请输入字段注释" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="插入位置：" name="afterColumnName">
						<a-select
							v-model:value="formData.afterColumnName"
							:options="columnList"
							style="width: 100%"
							placeholder="请输入插入位置（在某个字段名之后）"
						/>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">确认</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import dmApi from '@/api/dev/dmApi'
	import tool from '@/utils/tool'
	// 抽屉状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	// 定义
	const dbsList = ref([])
	const tableList = ref([])
	const columnList = ref([])
	const columnTypeOptions = tool.dictList('MYSQL_COLUMN_TYPE')
	const submitLoading = ref(false)

	const isEdit = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		initData(record)
	}

	// 初始化基础
	const initData = (record) => {
		dmApi.dbInfoList().then((data) => {
			dbsList.value = data.map((item) => {
				return {
					value: item['id'],
					label: item['poolName']
				}
			})
		})
		if (record) {
			let recordData = cloneDeep(record)
			isEdit.value = recordData.isEdit
			if (isEdit.value) {
				recordData.isEdit = undefined
				recordData.newColumnName = recordData.columnName
			} else {
				recordData.columnLength = 0
			}
			formData.value = Object.assign({}, recordData)
			getDbTables(record.dbsId)
			getDbColumns(record.dbsId, record.tableName)
		}
	}

	// 获取表
	const getDbTables = (dbsId) => {
		const param = {
			dbsId: dbsId
		}
		dmApi.tables(param).then((data) => {
			tableList.value = data.map((item) => {
				return {
					value: item['tableName'],
					label: `${item['tableRemark']}-${item['tableName']}`
				}
			})
		})
	}
	// 获取字段
	const getDbColumns = (dbsId, tableName) => {
		const param = {
			dbsId: dbsId,
			tableName: tableName
		}
		dmApi.columns(param).then((data) => {
			columnList.value = []
			data.forEach((item, index) => {
				if (isEdit.value && item['columnName'] === formData.value.columnName) {
					if (index > 0) {
						formData.value.afterColumnName = data[index - 1]['columnName']
					}
				} else {
					columnList.value.push({
						value: item['columnName'],
						label: `${item['columnRemark']}-${item['columnName']}`
					})
				}
			})
		})
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		dbsId: [required('请选择数据源')],
		tableName: [required('请选择表')],
		tableColumn: [required('请选择字段')],
		columnName: [required('请输入字段名称')],
		newColumnName: [required('请输入字段名称')],
		columnType: [required('请输入字段类型')],
		columnRemark: [required('请输入字段注释')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				if (!isEdit.value) {
					dmApi
						.addColumn(formDataParam)
						.then(() => {
							onClose()
							emit('successful')
						})
						.finally(() => {
							submitLoading.value = false
						})
				} else {
					dmApi
						.editColumn(formDataParam)
						.then(() => {
							onClose()
							emit('successful')
						})
						.finally(() => {
							submitLoading.value = false
						})
				}
			})
			.catch(() => {})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
